package com.sxt.core.net.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.sxt.core.anno.AutoBuilder;
import com.sxt.core.net.NetServerService;
import com.sxt.core.util.ThreadLocalUtil;

/**
 * IO :BIO 阻塞的io
 * 1 accept
 * 2 read() 阻塞
 * 3 write() 阻塞
 * @author WHSXT-LTD
 * 
 * 参考 NIo 和 Netty 的实现
 *
 */
@AutoBuilder
public class IOSocketNetServiceImpl implements NetServerService{

	private ServerSocket serverSocket ;

	@Override
	public InputStream getInputStream() {
		InputStream inputStream = null ;
		try {
			Socket client = serverSocket.accept(); // 获取客户端的链接。 它是阻塞的
			inputStream = client.getInputStream();
			ThreadLocalUtil.setValue("client", client);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return inputStream;
	}

	@Override
	public OutputStream getOutputStream() {
		Socket client = (Socket)ThreadLocalUtil.getValue("client");
		OutputStream outputStream = null ;
		try {
			outputStream = client.getOutputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return outputStream;
	}

	@Override
	public void bind(int port) {
		try {
			serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
